package com.example.homework

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import kotlin.random.Random

class GameView : View {
    // 游戏常量
    private val GRID_SIZE = 30       // 网格大小（像素）
    private val INIT_SPEED = 300     // 初始速度（毫秒/步）
    private val SPEED_DECREASE = 20  // 等级提升后速度减少量
    private val MAX_LEVEL = 10       // 最高等级

    // 连续点击提速相关变量
    var clickCount = 0 // 连续点击计数器（公开供Activity访问）
    val CLICK_INTERVAL = 500 // 连续点击判定间隔（毫秒）
    var lastClickTime = 0L // 上次点击时间（公开供Activity访问）
    private val MAX_CLICK_SPEED = 50 // 点击提速的最大速度（最小延迟）
    private val CLICK_SPEED_DECREASE = 15 // 每次连续点击减少的延迟（毫秒）

    // 方向常量
    companion object {
        const val UP = 0
        const val RIGHT = 1
        const val DOWN = 2
        const val LEFT = 3
    }

    // 游戏状态
    private var direction = RIGHT
    private var nextDirection = RIGHT
    private val snake = mutableListOf<IntArray>() // 蛇身：存储每节[x,y]坐标
    private val food = IntArray(2)               // 食物坐标[x,y]
    private var foodType: FoodType = FoodType.NORMAL // 当前食物类型
    private var foodColor: Int = Color.RED       // 当前食物颜色
    private var score = 0
    private var level = 1
    private var isGameOver = false
    private var isRunning = false

    // 食物类型枚举
    enum class FoodType {
        NORMAL,      // 普通食物：+10分，无特殊效果
        HIGH_SCORE,  // 高分食物：+30分
        SLOW_DOWN    // 减速食物：+10分，蛇速降低10%
    }

    // 食物颜色列表
    private val foodColorList = listOf(
        Color.RED, Color.YELLOW, Color.BLUE, Color.MAGENTA, Color.CYAN
    )

    // 绘图工具
    private val snakePaint = Paint().apply {
        color = Color.GREEN
        style = Paint.Style.FILL
    }
    private val textPaint = Paint().apply {
        color = Color.WHITE
        textSize = 40f
        textAlign = Paint.Align.CENTER
    }
    private val foodTipPaint = Paint().apply {
        color = Color.WHITE
        textSize = 16f
        textAlign = Paint.Align.CENTER
    }

    // 游戏线程
    private lateinit var gameThread: GameThread

    // 游戏结束回调接口
    private var listener: GameListener? = null
    interface GameListener {
        fun onGameOver(score: Int)
    }

    // 构造方法
    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    // 初始化游戏
    private fun init() {
        // 初始化蛇身
        snake.add(intArrayOf(5, 5))
        snake.add(intArrayOf(4, 5))
        snake.add(intArrayOf(3, 5))

        val maxX = if (width == 0) 20 else (width / GRID_SIZE - 1)
        val maxY = if (height == 0) 20 else (height / GRID_SIZE - 1)
        val randomX = if (maxX >= 20) Random.nextInt(10, 21) else Random.nextInt(10, maxX + 1)
        val randomY = if (maxY >= 20) Random.nextInt(10, 21) else Random.nextInt(10, maxY + 1)
        food[0] = randomX
        food[1] = randomY
        foodType = FoodType.NORMAL
        foodColor = Color.RED

        // 停止旧线程
        if (::gameThread.isInitialized && gameThread.isAlive) {
            gameThread.interrupt()
        }
        // 启动新线程
        val initialDelay = INIT_SPEED - (level - 1) * SPEED_DECREASE
        gameThread = GameThread(Math.max(initialDelay, 50))
        gameThread.start()
    }

    // 生成随机食物
    private fun generateFood() {
        if (width == 0 || height == 0) return

        val gridCountX = width / GRID_SIZE
        val maxX = if (gridCountX <= 1) 1 else gridCountX - 1

        val gridCountY = height / GRID_SIZE
        val maxY = if (gridCountY <= 1) 1 else gridCountY - 1

        if (maxX <= 0 || maxY <= 0) return

        var isOnSnake: Boolean
        do {
            isOnSnake = false
            food[0] = Random.nextInt(maxX)
            food[1] = Random.nextInt(maxY)

            foodType = when (Random.nextInt(10)) {
                0, 1 -> FoodType.HIGH_SCORE
                2, 3, 4, 5 -> FoodType.SLOW_DOWN
                else -> FoodType.NORMAL
            }
            foodColor = foodColorList[Random.nextInt(foodColorList.size)]

            for (part in snake) {
                if (part[0] == food[0] && part[1] == food[1]) {
                    isOnSnake = true
                    break
                }
            }
        } while (isOnSnake)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        if (oldw == 0 && oldh == 0 && !isRunning) {
            generateFood()
        }
    }

    // 开始游戏
    fun startGame() {
        isGameOver = false
        isRunning = true
        score = 0
        level = 1
        direction = RIGHT
        nextDirection = RIGHT
        clickCount = 0 // 重置点击计数器
        lastClickTime = 0L // 重置点击时间

        snake.clear()
        snake.add(intArrayOf(5, 5))
        snake.add(intArrayOf(4, 5))
        snake.add(intArrayOf(3, 5))

        generateFood()

        if (::gameThread.isInitialized && gameThread.isAlive) {
            gameThread.interrupt()
        }
        val initialDelay = INIT_SPEED - (level - 1) * SPEED_DECREASE
        gameThread = GameThread(Math.max(initialDelay, 50))
        gameThread.start()

        invalidate()
    }

    fun setDirection(newDir: Int) {
        when (direction) {
            UP -> if (newDir != DOWN) nextDirection = newDir
            RIGHT -> if (newDir != LEFT) nextDirection = newDir
            DOWN -> if (newDir != UP) nextDirection = newDir
            LEFT -> if (newDir != RIGHT) nextDirection = newDir
        }
    }

    // 连续点击提速方法
    fun speedUpByClick() {
        if (!isRunning || isGameOver) return

        val newDelay = gameThread.getCurrentDelay() - CLICK_SPEED_DECREASE
        val finalDelay = Math.max(newDelay, MAX_CLICK_SPEED)
        gameThread.updateDelay(finalDelay)
    }

    // 暂停游戏
    fun pauseGame() {
        isRunning = false
    }

    fun setGameListener(listener: GameListener) {
        this.listener = listener
    }

    fun getCurrentScore(): Int {
        return score
    }

    fun getCurrentLevel(): Int {
        return level
    }

    // 绘制游戏界面
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawColor(Color.BLACK)

        // 绘制蛇身
        for (part in snake) {
            canvas.drawRect(
                (part[0] * GRID_SIZE).toFloat(),
                (part[1] * GRID_SIZE).toFloat(),
                ((part[0] + 1) * GRID_SIZE).toFloat(),
                ((part[1] + 1) * GRID_SIZE).toFloat(),
                snakePaint
            )
        }

        // 绘制食物
        val foodPaint = Paint().apply {
            color = foodColor
            style = Paint.Style.FILL
        }
        canvas.drawCircle(
            (food[0] + 0.5f) * GRID_SIZE,
            (food[1] + 0.5f) * GRID_SIZE,
            GRID_SIZE / 2f,
            foodPaint
        )

        // 绘制食物效果提示
        val tipText = when (foodType) {
            FoodType.HIGH_SCORE -> "+30"
            FoodType.SLOW_DOWN -> "减速"
            FoodType.NORMAL -> ""
        }
        if (tipText.isNotEmpty()) {
            canvas.drawText(
                tipText,
                (food[0] + 0.5f) * GRID_SIZE,
                (food[1] + 0.5f) * GRID_SIZE - GRID_SIZE / 2f,
                foodTipPaint
            )
        }
    }

    // 触摸事件
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) {
            if (isGameOver) {
                startGame()
                return true
            }

            val centerX = width / 2f
            val centerY = height / 2f
            val touchX = event.x
            val touchY = event.y

            if (Math.abs(touchX - centerX) > Math.abs(touchY - centerY)) {
                if (touchX > centerX && direction != LEFT) {
                    nextDirection = RIGHT
                } else if (touchX < centerX && direction != RIGHT) {
                    nextDirection = LEFT
                }
            } else {
                if (touchY > centerY && direction != UP) {
                    nextDirection = DOWN
                } else if (touchY < centerY && direction != DOWN) {
                    nextDirection = UP
                }
            }
            return true
        }
        return super.onTouchEvent(event)
    }

    // 游戏线程
    inner class GameThread(private var currentDelay: Int) : Thread() {
        fun getCurrentDelay(): Int {
            return currentDelay
        }

        fun updateDelay(newDelay: Int) {
            currentDelay = Math.max(newDelay, 50)
        }

        override fun run() {
            while (isRunning && !isGameOver) {
                moveSnake()
                postInvalidate()

                try {
                    Thread.sleep(currentDelay.toLong())
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                    break
                }
            }
        }
    }

    // 移动蛇
    private fun moveSnake() {
        if (width == 0 || height == 0) return

        direction = nextDirection
        val head = snake[0]
        var newHeadX = head[0]
        var newHeadY = head[1]

        when (direction) {
            UP -> newHeadY--
            RIGHT -> newHeadX++
            DOWN -> newHeadY++
            LEFT -> newHeadX--
        }

        // 边界碰撞检测
        val maxX = width / GRID_SIZE - 1
        val maxY = height / GRID_SIZE - 1
        if (newHeadX < 0 || newHeadX > maxX || newHeadY < 0 || newHeadY > maxY) {
            gameOver()
            return
        }

        // 自身碰撞检测
        for (part in snake) {
            if (part[0] == newHeadX && part[1] == newHeadY) {
                gameOver()
                return
            }
        }

        // 添加新蛇头
        snake.add(0, intArrayOf(newHeadX, newHeadY))

        // 吃食物检测
        if (newHeadX == food[0] && newHeadY == food[1]) {
            when (foodType) {
                FoodType.NORMAL -> score += 10
                FoodType.HIGH_SCORE -> score += 30
                FoodType.SLOW_DOWN -> {
                    score += 10
                    val slowDelay = (gameThread.getCurrentDelay() * 1.1).toInt()
                    gameThread.updateDelay(slowDelay)
                }
            }
            generateFood()

            // 等级提升逻辑（兼容点击提速）
            val newLevel = score / 50 + 1
            if (newLevel > level && newLevel <= MAX_LEVEL) {
                level = newLevel
                val levelDelay = INIT_SPEED - (level - 1) * SPEED_DECREASE
                val currentDelay = gameThread.getCurrentDelay()
                // 取等级延迟和当前延迟的较大值，避免等级提速覆盖点击提速
                val finalDelay = Math.max(levelDelay, currentDelay)
                gameThread.updateDelay(Math.max(finalDelay, MAX_CLICK_SPEED))
            }
        } else {
            snake.removeAt(snake.size - 1)
        }
    }

    // 游戏结束
    private fun gameOver() {
        isGameOver = true
        isRunning = false
        listener?.onGameOver(score)
    }
}